package com.example.sprintboot.service.impl;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.sprintboot.entity.Product;
import com.example.sprintboot.entity.ProductStatus;
import com.example.sprintboot.mapper.ProductMapper;
import com.example.sprintboot.service.ProductService;
import com.example.sprintboot.vo.ProductBannerVO;
import com.example.sprintboot.vo.ProductDetailVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class ProductServiceImpl implements ProductService {
    @Autowired
    private ProductMapper productMapper;

    @Override
    public IPage<Product> getProductPage(int page, int pageSize, String keyword, Integer categoryId, Integer status) {
        Page<Product> p = new Page<>(page, pageSize);
        return productMapper.selectProductPage(p, keyword, categoryId, status);
    }

    @Override
    public Product getProductById(Integer productId) {
        return productMapper.selectById(productId);
    }

    @Override
    public boolean addProduct(Product product, Integer userId, String role) {
        // 卖家只能添加自己的商品，管理员可指定sellerId
        if (!"admin".equalsIgnoreCase(role)) {
            product.setSellerId(userId);
        }
        // 新增商品默认待审核
        product.setStatus(ProductStatus.PENDING);
        // 分类ID校验
        if (product.getCategoryId() == null) {
            return false;
        }
        return productMapper.insert(product) > 0;
    }

    @Override
    public boolean updateProduct(Product product, Integer userId, String role) {
        Product dbProduct = productMapper.selectById(product.getProductId());
        if (dbProduct == null) return false;
        // 卖家只能编辑自己的商品
        if (!"admin".equalsIgnoreCase(role) && !dbProduct.getSellerId().equals(userId)) {
            return false;
        }
        // 只允许部分字段可编辑
        dbProduct.setName(product.getName());
        dbProduct.setPrice(product.getPrice());
        dbProduct.setStock(product.getStock());
        dbProduct.setCategoryId(product.getCategoryId());
        dbProduct.setMainImage(product.getMainImage());
        dbProduct.setDescription(product.getDescription());
        dbProduct.setStatus(product.getStatus());
        return productMapper.updateById(dbProduct) > 0;
    }

    @Override
    public boolean deleteProduct(Integer productId, Integer userId, String role) {
        Product dbProduct = productMapper.selectById(productId);
        if (dbProduct == null) return false;
        // 卖家只能删除自己的商品
        if (!"admin".equalsIgnoreCase(role) && !dbProduct.getSellerId().equals(userId)) {
            return false;
        }
        return productMapper.deleteById(productId) > 0;
    }
    
    @Override
    public List<ProductBannerVO> getBannerProducts() {
        return productMapper.selectBannerProducts();
    }

    @Override
    public ProductDetailVO getProductDetailById(Integer productId) {
        return productMapper.selectProductDetailById(productId);
    }

    @Override
    public List<Product> getProductsBySellerId(Integer sellerId) {
        return productMapper.selectBySellerId(sellerId);
    }
    
    @Override
    public int getProductCountBySellerId(Integer sellerId) {
        return productMapper.selectCountBySellerId(sellerId);
    }
    
    @Override
    public boolean updateProductStatus(Integer productId, Integer sellerId, String status) {
        Product product = productMapper.selectById(productId);
        if (product == null || !product.getSellerId().equals(sellerId)) {
            return false;
        }
        product.setStatus(ProductStatus.valueOf(status));
        return productMapper.updateById(product) > 0;
    }

    // 管理员端商品管理相关方法实现
    @Override
    public IPage<Product> adminListProducts(int page, int pageSize, String keyword, String status, Integer categoryId) {
        Page<Product> productPage = new Page<>(page, pageSize);
        com.baomidou.mybatisplus.core.conditions.query.QueryWrapper<Product> wrapper = new com.baomidou.mybatisplus.core.conditions.query.QueryWrapper<>();
        
        // 关键词搜索
        if (keyword != null && !keyword.trim().isEmpty()) {
            wrapper.like("name", keyword.trim());
        }
        
        // 状态筛选
        if (status != null && !status.trim().isEmpty()) {
            wrapper.eq("status", status);
        }
        
        // 分类筛选
        if (categoryId != null) {
            wrapper.eq("category_id", categoryId);
        }
        
        // 按创建时间倒序
        wrapper.orderByDesc("create_time");
        
        return productMapper.selectPage(productPage, wrapper);
    }

    @Override
    public void approveProduct(Long id) {
        Product product = productMapper.selectById(id);
        if (product != null) {
            product.setStatus(ProductStatus.ON_SALE);
            productMapper.updateById(product);
        }
    }

    @Override
    public void rejectProduct(Long id) {
        Product product = productMapper.selectById(id);
        if (product != null) {
            product.setStatus(ProductStatus.REJECTED);
            productMapper.updateById(product);
        }
    }

    @Override
    public void onSaleProduct(Long id) {
        Product product = productMapper.selectById(id);
        if (product != null) {
            product.setStatus(ProductStatus.ON_SALE);
            productMapper.updateById(product);
        }
    }

    @Override
    public void offSaleProduct(Long id) {
        Product product = productMapper.selectById(id);
        if (product != null) {
            product.setStatus(ProductStatus.OFF_SHELF);
            productMapper.updateById(product);
        }
    }

    @Override
    public void updateProductByAdmin(Long id, Product product) {
        product.setProductId(id.intValue());
        productMapper.updateById(product);
    }

    @Override
    public void deleteProductByAdmin(Long id) {
        productMapper.deleteById(id);
    }

    @Override
    public boolean setBannerStatus(Long productId, boolean isBanner) {
        if (isBanner) {
            // 设为轮播图前先查当前已设数量，最多3个
            int count = productMapper.countBannerProducts();
            Product product = productMapper.selectById(productId);
            if (product == null) return false;
            if (!Boolean.TRUE.equals(product.getIsBanner()) && count >= 3) {
                // 已经有3个且当前不是轮播图，不能再设
                return false;
            }
            product.setIsBanner(true);
            return productMapper.updateById(product) > 0;
        } else {
            Product product = productMapper.selectById(productId);
            if (product == null) return false;
            product.setIsBanner(false);
            return productMapper.updateById(product) > 0;
        }
    }

    @Override
    public int countBannerProducts() {
        return productMapper.countBannerProducts();
    }
} 